package io.lb.deng.webflux.web.component;

import java.util.Date;

import org.springframework.stereotype.Component;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * jwt token 工具
 * @author DengLibin
 * @date ###### Sat Oct 2 11:08:41 CST 2021
 */
@Component
public class JwtTokenProvider {

    private static final String KEY = "qIjsO0Ps#@sisM&S";
    private static final long VALID_TIME = 24 * 60 * 60 * 1000; // TOKEN 有效期
    private static final String USER_ID_KEY = "USER_ID";
    private static final String USER_PERMISSION_KEY = "USER_PERMISSION";

    /**
     * 创建token
     * 
     * @param username 用户名
     * @param userId   用户id
     * @param rolePermissions 角色和权限
     * @return
     */
    public String createToken(String username, Long userId, String rolePermissions) {

        Claims claims = Jwts.claims().setSubject(username);
        claims.put(USER_ID_KEY, userId);
        claims.put(USER_PERMISSION_KEY, rolePermissions);

        Date now = new Date();
        Date validity = new Date(now.getTime() + VALID_TIME);

        return Jwts.builder().setClaims(claims).setIssuedAt(now).setExpiration(validity)
                .signWith(SignatureAlgorithm.HS256, KEY.getBytes()).compact();

    }

    /**
     * 获取用户名
     * 
     * @param token
     * @return
     */
    public String getUsername(String token) {
        Claims claims = Jwts.parser().setSigningKey(KEY.getBytes()).parseClaimsJws(token).getBody();
        return claims.getSubject();
    }

    /**
     * 获取用户id
     * 
     * @param token
     * @return
     */
    public Long getUserId(String token) {
        Claims claims = Jwts.parser().setSigningKey(KEY.getBytes()).parseClaimsJws(token).getBody();
        Object userId = claims.get(USER_ID_KEY);
        return Long.parseLong(userId.toString());
    }

    /**
     * 获取权限
     * @param token
     * @return
     */
    public String getRolePermissions(String token){
        Claims claims = Jwts.parser().setSigningKey(KEY.getBytes()).parseClaimsJws(token).getBody();
        Object permissions = claims.get(USER_PERMISSION_KEY);
        if(permissions == null) {
            return "";
        }
        return permissions.toString();
    }

    /**
     * 校验token
     * 
     * @param token
     * @return
     */
    public boolean validateToken(String token) {
        try {
            Jws<Claims> claims = Jwts.parser().setSigningKey(KEY.getBytes()).parseClaimsJws(token);
            return !claims.getBody().getExpiration().before(new Date());
        } catch (JwtException | IllegalArgumentException e) {
            e.printStackTrace();
            return false;
        }
    }
}
